dojo.provide('flickr.Flickr');

dojo.declare('flickr.Flickr', null, {
  constructor: function(api_key) {
    this.api_key = api_key;
    
    this._declare('people');
  },
  
  _declare: function() {
    for (var i = 0; i < arguments.length; i++) {
      var ns = arguments[i];
      var context = dojo.getObject(ns, true, this);
      if (!context.__noSuchMethod__) context.__noSuchMethod__ = this._createCaller(ns);
    }
  },
  
  _createCaller: function(ns) {
    return dojo.hitch(this, function(method, args) {
      var kwargs = args[0];
      kwargs.method = 'flickr.' + ns + '.' + method;
      return this._get(kwargs);
    });
  },
  
  _get: function(kwargs) {
    // This should be a Dojo transport!
    
    kwargs.api_key        = kwargs.api_key || this.api_key;
    kwargs.format         = 'json';
    kwargs.nojsoncallback = '1';
    
    var url = flickr.Flickr.END_POINT;
    for (var arg in kwargs) {
      if (kwargs.hasOwnProperty(arg)) url += arg + '=' + encodeURI(kwargs[arg]) + '&';
    }
    
    var response = readUrl(url);
    return dojo.fromJson(response);
  },
});

flickr.Flickr.END_POINT = 'http://api.flickr.com/services/rest/?';

flickr.Flickr.toPhotoUrl = function(photo) {
  return 'http://farm' + photo.farm + '.static.flickr.com/' + photo.server + '/' + photo.id + '_' + photo.secret + '.jpg';
};

flickr.Flickr.findUsernameByUrl = function(url) {
  var html = readUrl(url);
  var title = html.match(/<title>Flickr: (.*?)'s Photostream<\/title>/);
  if (title) return title[1];
  
  var creator = html.match(/<dc:creator><Agent><dc:title>(.*?)<\/dc:title><\/Agent><\/dc:creator>/)
  if (creator) return creator[1];
  
  return '';
};

flickr.Flickr.findUsernameByUrlName = function(name) {
  return flickr.Flickr.findUsernameByUrl('http://flickr.com/photos/' + name);
};
